﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Cms.Domain;
using Cms.Utilities;

namespace Cms.Web.Framework.DashboardGadgets
{
    public class MostPopularPages : BaseGadget
    {
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                var rpPages = (Repeater)FindControl("rpPages");
                var lblNoHits = (Label)FindControl("lblNoHits");
                rpPages.ItemDataBound += rpPages_ItemDataBound;
                rpPages.DataSource = GetMostVisitedPages();
                rpPages.DataBind();
                lblNoHits.Visible = rpPages.Items.Count == 0;
            }
            catch (Exception ex)
            {
                Logging.LogError("MostPopularPages", ex);
                Controls.Clear();
            }
        }

        protected IList<Page> GetMostVisitedPages()
        {
            return RepositoryFactory.PageRepository.GetMostVisitedPages(Administrator.CurrentSite.ID);
        }

        protected void rpPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var page = (Page)e.Item.DataItem;
            var litName = (Literal)e.Item.FindControl("litName");
            var litUrl = (Literal)e.Item.FindControl("litUrl");
            var litHits = (Literal)e.Item.FindControl("litHits");
            litName.Text = page.Name;
            litUrl.Text = page.GetVirtualPath();
            litHits.Text = page.Hits.ToString();
        }
    }
}